//
//  KZVocabularyImproveTestStatusView.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/8/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZVocabularyImproveTestStatusView.h"



// view
#import "KZAudioPlayOrRecordView.h"         // 播放和录制时间动效图
#import "KZResultView.h"                    // 结果
#import "KZLetterAnalysisView.h"            // 解析视图
#import "KZShadowButton.h"                  // 阴影按钮
#import "KZWaveRecordingView.h"             // 录制中水波动图
#import "KZBarWaveView.h"
#import "DicMainView.h"

// tool
#import "BKAudioPlayer.h"                   // 音视频播放
#import "KYTestEngine.h"                    // 口语评测


/**
 学习状态视图
 1.听标准发音
 2.准备点击录音，自己发音
 3.自己发音，复读三遍
 4.系统评测
 5.显示评测结果
 5.评测不合格
 -5.1.评测合格，直接下一个词汇
 -5.2.1.首次不合格，要求再次复读一次
 -5.2.2.再次不合格，显示该单词的所有资料（音标等），并在底部显示再“读一遍”和“下一个”2个按钮
 */

@implementation KZVocabularyImproveTestStatusView
{
    BOOL                    _isPass;
    NSInteger               _time;
    dispatch_block_t        _playAudioTask;
    
    BKAudioPlayer           *_audioPlayer;
    
    
    NSString                *_recordResult;             // 首次录音结果
    NSString                *_recordRepeatResult;       // 复读录音结果

    
    // 所有状态均存在
    UIImageView             *_letterBgView;             // 单词背景视图，一只企鹅
    UILabel                 *_letterLabel;              // 单词
    UIButton                *_playVoiceButton;          // 播放音频的按钮
    UIButton                *_coursewareButton;         // 课件按钮：显示课件解析
    
    // 1.听标准发音
    UIView                  *_status1View;              // 状态1的视图，方便隐藏，后面也一样
    KZAudioPlayOrRecordView *_audioPlayView;            // 播放时长
    UILabel                 *_status1NoteLabel;         // 请听标准发音
    
    
    // 2.准备点击录音，自己发音
    UIView                  *_status2View;
    UILabel                 *_status2NoteLabel;         // 请按下面话咪开始复读
    UIButton                *_prepareRecordButton;      // 准备录制icon
    
    // 3.自己发音，复读三遍
    UIView                  *_status3View;
    UILabel                 *_status3NoteLabel;         // 复读三遍
    KZWaveRecordingView     *_recordingView;            // 录音中gif
    KZBarWaveView           *_recordingBarWaveView;     // 录制时长
    UILabel                 *_recordCountDownLabel;     // *秒后结束录音
    NSTimer                 *_timer;                    // 倒计时
    NSInteger               _timeCountDown;
    
    // 4.系统评测
    UIView                  *_status4View;
    UILabel                 *_status4NoteLabel;         // 系统正在给您评测，请稍候
    UIImageView             *_evaluatingView;           // 评测中
    
    // 5.1.评测合格，直接下一个词汇
    UIView                  *_status5_1View;
    KZResultView            *_successView;
    
    // 5.2.1首次不合格，要求再次复读一次，再复读用status3的视图，并修改noteLabel的文案（改为正在复读一遍）
    UIView                  *_status5_2_1View;
    KZResultView            *_failureView;
    
    
    // 5.2.2再次不合格，显示发音图解视频和不合格字样，并在底部显示再“重新训练”和“下一个”2个按钮
    UIView                  *_status5_2_2View;          //
    KZLetterAnalysisView    *_analysisView;             // 课件解析
    KZResultView            *_finalFailureView;         // 最终失败
    UIButton                *_retrianButton;            // 重新训练
    KZShadowButton          *_nextButton;               // 下一个
    
    
}

- (void)dealloc {
    
    NSLog(@"销毁了");
}

- (instancetype)init {
    if (self = [super init]) {
#ifdef DEBUG
        [self test];
#endif
        
        _audioPlayer = [BKAudioPlayer new];
        _isPauseAtRecording = false;
    }
    return self;
}
- (void)setupUI {
    
    _letterBgView = [UIImageView new];
    _letterBgView.image = [UIImage imageNamed:@"kz-音标鸽子背景"];
    
    [self addSubview:_letterBgView];
    [_letterBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@50);
        make.centerX.equalTo(@0);
        if (iPhone5S) {
            make.height.equalTo(@160);
            make.width.equalTo(_letterBgView.mas_height).multipliedBy(525.0/431);
        }
    }];
    
    _letterLabel = [[UILabel alloc] init];
    _letterLabel.adjustsFontSizeToFitWidth = true;
    _letterLabel.numberOfLines = 1;
    _letterLabel.text = @"?";
    _letterLabel.font = B_FONT(45);
    _letterLabel.textAlignment = NSTextAlignmentCenter;
    _letterLabel.textColor = [UIColor whiteColor];
    [_letterBgView addSubview:_letterLabel];
    [_letterLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_letterBgView).offset(2);
        make.centerX.equalTo(@0);
        make.width.equalTo(_letterBgView).multipliedBy(350.0/525);
    }];
    
    _playVoiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playVoiceButton setImage:[UIImage imageNamed:@"kz-发音图标"] forState:UIControlStateNormal];
    [_playVoiceButton addTarget:self action:@selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_playVoiceButton];
    [_playVoiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_letterBgView).offset(10);
        make.width.height.mas_equalTo(W(44));
        make.centerX.equalTo(@0);
    }];
    
    _coursewareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _coursewareButton.hidden = true;
    [_coursewareButton setImage:[UIImage imageNamed:@"kz-解析课件"] forState:UIControlStateNormal];
    [_coursewareButton addTarget:self action:@selector(analyze:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_coursewareButton];
    [_coursewareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_letterBgView).offset(10);
        make.width.height.mas_equalTo(W(44));
        make.centerX.equalTo(@0);
    }];
}
// 1.听标准发音
- (void)setupStatus1View {
    
    _status1View = [UIView new];
    [self addSubview:_status1View];
    [_status1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(_playVoiceButton.mas_bottom);
        make.bottom.equalTo(@0);
    }];
    
    _audioPlayView = [KZAudioPlayOrRecordView new];
    [_status1View addSubview:_audioPlayView];
    [_audioPlayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(4*10 + 6*8 + 40 + 10));
        make.top.equalTo(@0);
        make.centerX.equalTo(@0);
        make.height.equalTo(@30);
    }];
    
    _status1NoteLabel = [[UILabel alloc] init];
    _status1NoteLabel.adjustsFontSizeToFitWidth = true;
    _status1NoteLabel.numberOfLines = 1;
    _status1NoteLabel.text = @"请听标准发音...";
    _status1NoteLabel.font = FONT(14);
    _status1NoteLabel.textAlignment = NSTextAlignmentCenter;
    _status1NoteLabel.textColor = [UIColor grayColor];
    [_status1View addSubview:_status1NoteLabel];
    [_status1NoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.bottom.equalTo(_status1View.mas_centerY).offset(-10);
    }];
}

// 2.准备点击录音，自己发音
- (void)setupStatus2View {
    
    _status2View = [UIView new];
    _status2View.hidden = true;
    [self addSubview:_status2View];
    [_status2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(_playVoiceButton.mas_bottom);
        make.bottom.equalTo(@0);
    }];
    
    _prepareRecordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_prepareRecordButton setBackgroundImage:[UIImage imageNamed:@"kz-话咪背景"] forState:UIControlStateNormal];
    [_prepareRecordButton setImage:[UIImage imageNamed:@"kz-话咪"] forState:UIControlStateNormal];
    [_status2View addSubview:_prepareRecordButton];
    [_prepareRecordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_status2View.mas_centerY).offset(-20);
        make.centerX.equalTo(@0);
    }];
    
    _status2NoteLabel = [[UILabel alloc] init];
    _status2NoteLabel.adjustsFontSizeToFitWidth = true;
    _status2NoteLabel.numberOfLines = 1;
    _status2NoteLabel.text = @"请按下面的话咪开始复读";
    _status2NoteLabel.font = FONT(14);
    _status2NoteLabel.textAlignment = NSTextAlignmentCenter;
    _status2NoteLabel.textColor = [UIColor grayColor];
    [_status2View addSubview:_status2NoteLabel];
    [_status2NoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.bottom.equalTo(_prepareRecordButton.mas_top).offset(-10);
    }];
    
    
}

// 3.自己发音，复读三遍
- (void)setupStatus3View {
    
    _status3View = [UIView new];
    _status3View.hidden = true;
    [self addSubview:_status3View];
    [_status3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(_playVoiceButton.mas_bottom);
        make.bottom.equalTo(@0);
    }];
    
    _recordingView = [KZWaveRecordingView new];
    [_status3View addSubview:_recordingView];
    [_recordingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_status3View.mas_centerY).offset(-20);
        make.centerX.equalTo(@0);
        make.width.height.mas_equalTo(W(70));
    }];
    
    
    _status3NoteLabel = [[UILabel alloc] init];
    _status3NoteLabel.adjustsFontSizeToFitWidth = true;
    _status3NoteLabel.numberOfLines = 1;
    _status3NoteLabel.text = @"请复读3遍...";
    _status3NoteLabel.font = FONT(14);
    _status3NoteLabel.textAlignment = NSTextAlignmentCenter;
    _status3NoteLabel.textColor = [UIColor grayColor];
    [_status3View addSubview:_status3NoteLabel];
    [_status3NoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.bottom.equalTo(_recordingView.mas_top).offset(-10);
    }];
    
    
    
    _recordingBarWaveView = [KZBarWaveView new];
    [_status3View addSubview:_recordingBarWaveView];
    [_recordingBarWaveView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(4*10 + 6*8 + 10));
        make.centerX.equalTo(@0);
        make.height.equalTo(@30);
        make.top.equalTo(_recordingView.mas_bottom).offset(0);
    }];
    
    _recordCountDownLabel = [[UILabel alloc] init];
    _recordCountDownLabel.adjustsFontSizeToFitWidth = true;
    _recordCountDownLabel.numberOfLines = 1;
    _recordCountDownLabel.text = @"5秒后结束录音...";
    _recordCountDownLabel.font = FONT(14);
    _recordCountDownLabel.textAlignment = NSTextAlignmentCenter;
    _recordCountDownLabel.textColor = [UIColor orangeColor];
    [_status3View addSubview:_recordCountDownLabel];
    [_recordCountDownLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.equalTo(_recordingBarWaveView.mas_bottom).offset(5);
    }];
}

// 4.系统评测
- (void)setupStatus4View {
    
    _status4View = [UIView new];
    _status4View.hidden = true;
    [self addSubview:_status4View];
    [_status4View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(_playVoiceButton.mas_bottom);
        make.bottom.equalTo(@0);
    }];
    
    _evaluatingView = [UIImageView new];
    [_evaluatingView gif:@"__4"];
    [_status4View addSubview:_evaluatingView];
    [_evaluatingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_status4View.mas_centerY).offset(-20);
        make.centerX.equalTo(@0);
        make.width.height.mas_equalTo(W(70));
    }];
    
    _status4NoteLabel = [[UILabel alloc] init];
    _status4NoteLabel.adjustsFontSizeToFitWidth = true;
    _status4NoteLabel.numberOfLines = 1;
    _status4NoteLabel.text = @"系统正在给您评判，请稍候...";
    _status4NoteLabel.font = FONT(14);
    _status4NoteLabel.textAlignment = NSTextAlignmentCenter;
    _status4NoteLabel.textColor = [UIColor grayColor];
    [_status4View addSubview:_status4NoteLabel];
    [_status4NoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.equalTo(_evaluatingView.mas_bottom).offset(10);
    }];
}
// 5.1.评测合格，直接下一个词汇
- (void)setupStatus5_1View {
    
    _status5_1View = [UIView new];
    _status5_1View.hidden = true;
    [self addSubview:_status5_1View];
    [_status5_1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(_playVoiceButton.mas_bottom);
        make.bottom.equalTo(@0);
    }];
    
    _successView = [KZResultView new];
    _successView.status = 0;
    [_status5_1View addSubview:_successView];
    [_successView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@60);
        make.left.right.equalTo(@0);
        make.top.equalTo(_status5_1View.mas_centerY).offset(-20);
    }];
    
}
// 5.2.1首次不合格，要求再次复读一次
- (void)setupStatus5_2_1View {
    
    _status5_2_1View = [UIView new];
    _status5_2_1View.hidden = true;
    [self addSubview:_status5_2_1View];
    [_status5_2_1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(_playVoiceButton.mas_bottom);
        make.bottom.equalTo(@0);
    }];
    
    _failureView = [KZResultView new];
    _failureView.status = 1;
    [_status5_2_1View addSubview:_failureView];
    [_failureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@60);
        make.left.right.equalTo(@0);
        make.top.equalTo(_status5_2_1View.mas_centerY).offset(-20);
    }];
    
}

// 5.2.2再次不合格，显示发音图解视频和不合格字样，并在底部显示再“重新训练”和“下一个”2个按钮
- (void)setupStatus5_2_2View {
    
    _status5_2_2View = [UIView new];
    _status5_2_2View.hidden = true;
    [self addSubview:_status5_2_2View];
    [_status5_2_2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(_playVoiceButton.mas_bottom);
        make.bottom.equalTo(@0);
    }];
    
    _retrianButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _retrianButton.titleLabel.font = FONT(18);
    _retrianButton.layer.cornerRadius = 4;
    _retrianButton.layer.masksToBounds = true;
    _retrianButton.layer.borderColor = [UIColor colorWithHex:0x12BCB7].CGColor;
    _retrianButton.layer.borderWidth = 1;
    [_retrianButton setTitle:@"再读一遍" forState:UIControlStateNormal];
    [_retrianButton setTitleColor:[UIColor colorWithHex:0x12BCB7] forState:UIControlStateNormal];
    [_retrianButton addTarget:self action:@selector(repeat) forControlEvents:UIControlEventTouchUpInside];
    [_status5_2_2View addSubview:_retrianButton];
    [_retrianButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_status5_2_2View.mas_centerX).offset(-5);
        make.left.equalTo(@20);
        make.bottom.equalTo(@-20);
        make.height.mas_equalTo(H(40));
    }];
    
    _nextButton = [[KZShadowButton alloc] init:^(UIButton *button) {
        button.titleLabel.font = FONT(18);
        [button setTitle:@"下一个" forState:UIControlStateNormal];
    }];
    [_nextButton addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [_status5_2_2View addSubview:_nextButton];
    [_nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_status5_2_2View.mas_centerX).offset(5);
        make.bottom.width.height.equalTo(_retrianButton);
    }];
    
    _finalFailureView = [KZResultView new];
    _finalFailureView.status = 2;
    [_status5_2_2View addSubview:_finalFailureView];
    [_finalFailureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@40);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(_nextButton.mas_top).offset(-20);
    }];
}

#pragma mark - setter
- (void)setModel:(KZVocabularyCurrentPackageDetailModel *)model {
    
    _model = model;
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    [self setupUI];
    [self setupStatus1View];
    [self setupStatus3View];
    [self setupStatus4View];
    [self setupStatus5_1View];
    [self setupStatus5_2_1View];
    [self setupStatus5_2_2View];
    
    // 如果是一个包的最后一题按钮和显示需要特殊处理一下
    if (_model.Index.integerValue == _packageModel.currentPackage.Detail.count) {
        [_nextButton.button setTitle:@"查看结果" forState:UIControlStateNormal];
        _successView.status = 10;
    }

    // 开始测试
    [self beginTest];
    
//    // 快速自动做题测试
//    if (model.Index.integerValue <= 19) {
//        if (model.Index.integerValue % 2 == 0) {
//            _isPass = true;
//            _model.IsPassed = @"1";
//            _model.UpdateTime = [NSDate date];
//
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                self.successStayBlock();
//            });
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                self.nextBlock();
//            });
//        } else {
//            _model.IsPassed = @"0";
//            _model.UpdateTime = [NSDate date];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                self.failureStayBlock();
//            });
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                self.nextBlock();
//            });
//        }
//    } else {
//        [self beginTest];
//    }
}



#pragma mark - 定时器和方法
// 开始测试，创建定时器
- (void)beginTest {
    
    _playVoiceButton.userInteractionEnabled = false;
    _coursewareButton.userInteractionEnabled = false;
    
    [_audioPlayView startSoucre];
    [_recordingBarWaveView startSoucre];
    _recordResult = nil;
    _recordRepeatResult = nil;
    _time = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:true];
    
}
- (void)timerAction:(NSTimer *)timer {
    
    _time ++;

    if (_time >= 40 && _time <= 90) {
        _recordCountDownLabel.text = [NSString stringWithFormat:@"%.0lf秒后结束录音", ceil((90 - _time) / 10.0)];
    } else if (_time >= 130 && _time <= 160) {
        _recordCountDownLabel.text = [NSString stringWithFormat:@"%.0lf秒后结束录音", ceil((160 - _time) / 10.0)];
    }
    
    // 1.准备播放 1
    if (_time == 10) {
        [self _playAudio];
    }
    // 2.播放3秒后，关闭音频，并开启录音 1+3=4
    else if (_time == 40) {
        [self _closeAudio];
    }
    // 3.录音5秒后，跳转到评测界面 4+5=9
    else if (_time == 90) {
        [self transition:_status3View toView:_status4View];
    }
    // 在评测界面停留2秒后，显示录音结果 9+2=11
    else if (_time == 110) {
        
        [[KYTestEngine sharedInstance] stopEngine];
        if (_recordResult == nil) {
            _time -= 1;
            return;
        }
        [self analyzeRecordResult];
    }
    // 2秒用于显示结果：通过或未通过 11+2=13
    else if (_time == 130) {
        if (_isPass) {
            [_timer invalidate];
            _timer = nil;
            if (_nextBlock) {
                _nextBlock();
            }
        } else {
            [self _prepareRecord2];
        }
    }
    // 第二次检测，录音三秒，跳转到评测界面 13+3=16
    else if (_time == 160) {
        [self transition:_status3View toView:_status4View];
    }
    // 在评测界面停留2秒后，显示录音结果 16+2=18
    else if (_time == 180) {
        [[KYTestEngine sharedInstance] stopEngine];
        if (_recordRepeatResult == nil) {
            _time -= 1;
            return;
        }
        [self analyzeRecordRepeatResult];
    }
    // 2秒用于显示结果：通过或未通过 18+2=20
    else if (_time == 200) {
        if (_isPass) {
            [_timer invalidate];
            _timer = nil;
//            if (_nextBlock) {
//                _nextBlock();
//            }
        } else {
            
        }
    }
    
}
// 开始播放音频
- (void)_playAudio {
    
    // 正在播放中，不播放
    if (_audioPlayer.player.status == MAudioStatePlaying) {
        return;
    }
    NSString *url = _model.VocabularyAudioPath;
    [_audioPlayer playerUrl:[NSURL URLWithString:url] seekTotime:0 rateValue:1];
    [_audioPlayer playerPlay];
    
    
}
// 关闭音频，并准备开始录音
- (void)_closeAudio {
    
    [self _prepareRecord];
    
    [_audioPlayer playerPaused];
    [_audioPlayer closePlayer];
    
}

// 分析录音结果
- (void)analyzeRecordResult {
    
    NSString *testResult = _recordResult;
    NSLog(@"%@", testResult);
    NSData *data = [testResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSInteger confidence = [dic[@"result"][@"overall"] integerValue];
    
    // 录音后显示文本
    _letterLabel.text = _model.Vocabulary;
    
    if (confidence > LS_System.vocabularyScore) {
        [self _pass:confidence];
    } else {
        [self _nopass1:confidence];
    }
}
// 分析复读录音结果
- (void)analyzeRecordRepeatResult {
    
    NSString *testResult = _recordRepeatResult;
    NSLog(@"%@", testResult);
    NSData *data = [testResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSInteger confidence = [dic[@"result"][@"overall"] integerValue];
    if (confidence > LS_System.vocabularyScore) {
        // 第二次检测通过
        [self _pass2];
    } else {
        // 第二次失败以后，不需要在用到定时器了，可以提前销毁，否则在等待2秒的过程中，如果用户点击了重做或下一题，将会产生2个定时器同时作用
        [_timer invalidate];
        _timer = nil;
        [self _nopass2];
    }
}

// 通关
- (void)_pass:(NSInteger)score {
    
    _isPass = true;
    _model.IsPassed = @"1";
    _model.UpdateTime = [NSDate date];
    _model.Score = @(score);
    [self transition:_status4View toView:_status5_1View];
    if (_successStayBlock) {
        _successStayBlock();
    }
}
- (void)_pass2 {
    
    _playVoiceButton.userInteractionEnabled = true;
    _coursewareButton.userInteractionEnabled = true;
    _finalFailureView.status = 3;
    [self transition:_status4View toView:_status5_2_2View];
}
// 第1次未通过
- (void)_nopass1:(NSInteger)score {
    
    _isPass = false;
    _model.IsPassed = @"0";
    _model.UpdateTime = [NSDate date];
    _model.Score = @(score);
    [self transition:_status4View toView:_status5_2_1View];
    if (_failureStayBlock) {
        _failureStayBlock();
    }
}
// 第2次未通过
- (void)_nopass2 {

    _playVoiceButton.userInteractionEnabled = true;
    _coursewareButton.userInteractionEnabled = true;
    _finalFailureView.status = 2;
    [self transition:_status4View toView:_status5_2_2View];
}
// 第一次录音
- (void)_prepareRecord {
    
    [self transition:_status1View toView:_status3View];
    
    // 开始评测，倒计时5秒
    KYTestConfig *config = [[KYTestConfig alloc] init];
    config.coreType = KYTestType_Sentence;
    config.refText = [NSString stringWithFormat:@"%@ %@ %@", _model.Vocabulary, _model.Vocabulary, _model.Vocabulary];
    config.phonemeOption = KYPhonemeOption_KK;
    config.audioType = @"wav";
    config.sampleRate = 16000;
    config.sampleBytes = 2;
    [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
        
        _recordResult = testResult;
//        NSLog(@"%@", testResult);
//        NSData *data = [testResult dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        NSInteger confidence = [dic[@"result"][@"overall"] integerValue];
//
//        // 录音后显示文本
//        _letterLabel.text = _model.Vocabulary;
//
//        if (confidence > 80) {
//            [self _pass:confidence];
//        } else {
//            [self _nopass1:confidence];
//        }
    }];
   
}
// 第二次录音
- (void)_prepareRecord2 {
    
    _status3NoteLabel.text = @"请复读1遍...";
    [self transition:_status5_2_1View toView:_status3View];
    [self transition:_status5_2_2View toView:_status3View];

    // 复读一遍
    KYTestConfig *config = [[KYTestConfig alloc] init];
    config.coreType = KYTestType_Word;
    config.refText = [NSString stringWithFormat:@"%@", _model.Vocabulary];
    config.phonemeOption = KYPhonemeOption_KK;
    config.audioType = @"wav";
    config.sampleRate = 16000;
    config.sampleBytes = 2;
    [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
        
        _recordRepeatResult = testResult;
//        NSLog(@"%@", testResult);
//        NSData *data = [testResult dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        NSInteger confidence = [dic[@"result"][@"overall"] integerValue];
//        if (confidence > 80) {
//            // 第二次检测通过
//            [self _pass2];
//        } else {
//            // 第二次失败以后，不需要在用到定时器了，可以提前销毁，否则在等待2秒的过程中，如果用户点击了重做或下一题，将会产生2个定时器同时作用
//            [_timer invalidate];
//            _timer = nil;
//            [self _nopass2];
//        }
    }];
}


#pragma mark - 事件
// 播放音频
- (void)playAudio {
    
    // 正在播放中，不播放
    if (_audioPlayer.player.status == MAudioStatePlaying) {
        return;
    }
    
    NSString *url = _model.VocabularyAudioPath;
    [_audioPlayer playerUrl:[NSURL URLWithString:url] seekTotime:0 rateValue:1];
    [_audioPlayer playerPlay];
    
    // 播放2秒后暂停播放，并关闭播放器。首次播放则进入状态2界面
    __weak typeof(self) wself = self;
    _playAudioTask = [self beginBlockTask:^{
        __strong typeof(self) sself = wself;
        [sself->_audioPlayer playerPaused];
        [sself->_audioPlayer closePlayer];
    } after:3];

}
// 课件解析
- (void)analyze:(UIButton *)button {
    
    DicMainView *main = [[DicMainView alloc] initWithTestType:DictTestType_Word isShowRecord:YES];
    main.dictUrl = [NSString stringWithFormat:@"%@api/ZXYYTS/W_ZXYYTS_GetCoursewareByCode",KGetUserDefaults(@"SystemIP")];
    main.dictParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                       @"schoolId":DR_UserInfo.SchoolID,
                       @"stuId":DR_UserInfo.UserID,
                       @"knowledge": _model.VocabularyID,
                       @"levelCode": KGetUserDefaults(@"TestLayer")
                       };
    [main popAnimated:YES];
}
// 重读一遍
- (void)repeat {
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    _time = 128;
    _recordRepeatResult = nil;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:true];

}
- (void)nextAction {
    
    if (self.nextBlock) {
        self.nextBlock();
    }
}
#pragma mark - 辅助方法
// 状态视图转场动画
- (void)transition:(UIView *)fromView toView:(UIView *)toView {
    
    CATransition *ani = [CATransition animation];
    ani.type = kCATransitionFade;
    if (![self.layer animationForKey:@"Transition"]) {
        [self.layer addAnimation:ani forKey:@"Transition"];
    }
    fromView.hidden = true;
    toView.hidden = false;
    
    if (toView == _status5_2_2View) {

        _coursewareButton.hidden = false;
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.4 initialSpringVelocity:0 options:0 animations:^{
            [_playVoiceButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.mas_centerX).offset(-20);
            }];
            [_coursewareButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.mas_centerX).offset(20);
            }];
            [self layoutIfNeeded];
        } completion:^(BOOL finished) {
            if (finished) {
//                KZLetterAnalysisView *view = [KZLetterAnalysisView new];
//                view.model = _model;
//                view.tag = 1000;
//                // _coursewareButton在_status5_2_2View上的相对位置
//                CGRect rect = [self convertRect:_coursewareButton.frame toView:_status5_2_2View];
//                CGPoint point = CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height);
//                [view showWithPoint:point rect:CGRectMake(20, point.y, _status5_2_2View.width - 40, _finalFailureView.top - 10) view:_status5_2_2View];
            }
        }];

    }
}

// 开起一个延时任务
- (dispatch_block_t)beginBlockTask:(void(^)(void))block after:(NSTimeInterval)after {
    
    dispatch_block_t task = dispatch_block_create(DISPATCH_BLOCK_DETACHED, block);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(after * NSEC_PER_SEC)), dispatch_get_main_queue(), task);
    return task;
}

// 中途退出需要销毁定时器，播放中的音频，录音中的插件等
- (void)freeSource {
    
    if (_playAudioTask != NULL) {
        dispatch_block_cancel(_playAudioTask);
    }

    [_audioPlayView freeSource];
    [_recordingBarWaveView freeSource];
    
    [_timer invalidate];
    _timer = nil;

    [_audioPlayer playerPaused];
    [_audioPlayer closePlayer];
    
    [[KYTestEngine sharedInstance] cancelEngine];
}

- (void)pauseSource {
    [_audioPlayView pauseSource];
    [_recordingBarWaveView pauseSource];
    [_recordingView pauseSource];
//    [_evaluatingView stopAnimating];
//    [[KYTestEngine sharedInstance] pauseEngine];
    [_timer setFireDate:[NSDate distantFuture]];
    
    if (_time >= 40 && _time <= 90) {
        _time = 38;
        _isPauseAtRecording = true;
        [[KYTestEngine sharedInstance] cancelEngine];
    } else if (_time >= 130 && _time <= 160) {
        _time = 128;
        _isPauseAtRecording = true;
        [[KYTestEngine sharedInstance] cancelEngine];
    } else {
        _isPauseAtRecording = false;
    }
}
- (void)beginSource {
    [_audioPlayView beginSource];
    [_recordingBarWaveView beginSource];
    [_recordingView beginSource];
//    [_evaluatingView startAnimating];
//    [[KYTestEngine sharedInstance] resumeEngine];
    [_timer setFireDate:[NSDate date]];
}



#pragma mark - 测试
- (void)test {
    
    UILongPressGestureRecognizer *lp = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(__test:)];
    [self addGestureRecognizer:lp];
}
- (void)__test:(UILongPressGestureRecognizer *)lp {
    if (lp.state != UIGestureRecognizerStateEnded) {
        return;
    }
    NSLog(@"1");
    
    
    [self pauseSource];
    
    NSTimeInterval interval = 0;
    if (_timer.timeInterval < 0.05) {
        interval = 0.1;
    } else {
        interval = 0.01;
    }
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerAction:) userInfo:nil repeats:true];
    [self beginSource];
}

@end
